package com.qnzw.zjmy.home.fragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.android.volley.Request;
import com.anythink.nativead.api.ATNativeAdView;
import com.google.android.material.tabs.TabLayout;
import com.qnzw.zjmy.R;
import com.qnzw.zjmy.ad.MediationFeedAd;
import com.qnzw.zjmy.ad.MediationTablePlaqueAd;
import com.qnzw.zjmy.ad.kaku.interstitia.TaKuInterstitialAdHome;
import com.qnzw.zjmy.ad.kaku.nativie.TaKuNativeAdHome;
import com.qnzw.zjmy.adapter.ItemBannerAdapter;
import com.qnzw.zjmy.adapter.ItemCateHomeAdapter;
import com.qnzw.zjmy.adapter.ItemGoodsStyle1Adapter;
import com.qnzw.zjmy.config.UrlAddressConfig;
import com.qnzw.zjmy.config.UrlConfig;
import com.qnzw.zjmy.home.ui.adapter.GoodsAdapter;
import com.qnzw.zjmy.home.ui.enums.RedisEnum;
import com.qnzw.zjmy.home.ui.model.Banner;
import com.qnzw.zjmy.home.ui.model.Category;
import com.qnzw.zjmy.home.ui.model.Good;
import com.qnzw.zjmy.home.ui.model.vo.BaseVo;
import com.qnzw.zjmy.volley.BaseFragment;
import com.qnzw.zjmy.volley.state.HUCState;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

public class HomeFragment extends BaseFragment implements OnBannerListener {
    private View view;


    private ListView goodsGridView;
    private GoodsAdapter goodsAdapter;

    private List<Banner> bannerList;

    private boolean isVisibleToUser = false;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (ObjectUtil.isNotNull(view)) {
            return view;
        }
        view = inflater.inflate(R.layout.view_page_home, container, false);
        super.onCreateView(inflater, container, savedInstanceState);
//        ImmersionBar.with(this).titleBar(view.findViewById(R.id.home_title)).init();
        //Log.e("HomeFragment","token---- >>>>"+getSharedPreferences("deviceId"));
        initBanners();
        initGoods();
        return view;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        if (isVisibleToUser) {
            initAd();
        }
    }

    @Override
    public void initView() {
        super.initView();
        goodsGridView = view.findViewById(R.id.goods);
        initCate();
        initAd();
    }

    private void initCate() {
        hucRequestInterfase.executeStr(this, Category.class, HUCState.HUC_REQEUST_CODE_3, Request.Method.POST, UrlConfig.URL_PRO_CATEGORY, hucParameInterfase.getRequestParameter(new BaseVo()), false);
    }

    @Override
    public void onResume() {
        super.onResume();

    }
    ItemCateHomeAdapter itemCateHomeAdapter;
    @Override
    public void onSuccessfulStrType(int inputType, Object response) {
        switch (inputType) {
            case HUCState.HUC_REQEUST_CODE_1:
                if (!(response instanceof List)) {
                    return;
                }
                List<String> picUrls = new ArrayList<String>();
                bannerList = (List<com.qnzw.zjmy.home.ui.model.Banner>) response;
                if(!CollectionUtil.isEmpty(bannerList)){
                    RecyclerView bannerListView=view.findViewById(R.id.banner_list);
                    ItemBannerAdapter itemBannerAdapter = new ItemBannerAdapter(this.getContext(), bannerList);
                    LinearSnapHelper linearSnapHelper = new LinearSnapHelper();
                    linearSnapHelper.attachToRecyclerView(bannerListView);
                    bannerListView.setAdapter(itemBannerAdapter);
                }

                break;
            case HUCState.HUC_REQEUST_CODE_2:
                if (!(response instanceof List)) {
                    return;
                }
//                goodsAdapter = new GoodsAdapter(this.getContext(), (List<Good>) response);
//                goodsGridView.setAdapter(goodsAdapter);
                ItemGoodsStyle1Adapter itemGoodsStyle1Adapter=new ItemGoodsStyle1Adapter(this.getContext(), (List<Good>) response);
                RecyclerView listView=view.findViewById(R.id.goodsList);
                listView.setAdapter(itemGoodsStyle1Adapter);
                break;
            case HUCState.HUC_REQEUST_CODE_3:
                //分类
                if (!(response instanceof List)) {
                    return;
                }
                List<Category> categoryList=(List<Category>) response;
                initCategory(categoryList);
                break;
            case HUCState.HUC_REQEUST_CODE_4:
                //列表
                if (!(response instanceof List)) {
                    return;
                }
                List<Good> goodList=(List<Good>) response;
                RecyclerView goodsListView = view.findViewById(R.id.layoutList);

                if (itemCateHomeAdapter != null) {
                    itemCateHomeAdapter.refreshData(goodList);
                }else{
                    ItemCateHomeAdapter itemCateHomeAdapter=new ItemCateHomeAdapter(getContext(),goodList);
                    goodsListView.setAdapter(itemCateHomeAdapter);
                }

                break;
            default:
                break;
        }
    }

    public void initCategory(List<Category> categoryList){
        TabLayout tableLayout=view.findViewById(R.id.layoutTab);
        List<Fragment> fragmentList=new ArrayList<>();
        for (Category category : categoryList) {
            tableLayout.addTab(tableLayout.newTab().setText(category.getPcName()));
            fragmentList.add(new CategoryFragment());
        }
        if(categoryList.size()>0){
            String pId = categoryList.get(0).getId();
            if("全部".equals(categoryList.get(0).getPcName())){
                pId="";
            }
            searchGoodsById(pId);
        }
        tableLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int selectedTabPosition = tableLayout.getSelectedTabPosition();
                Category category = categoryList.get(selectedTabPosition);
                String pId = category.getId();
                if("全部".equals(category.getPcName())){
                    pId="";
                }
                searchGoodsById(pId);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

    }

    private void searchGoodsById(String pid) {
        BaseVo baseVo = new BaseVo();
        baseVo.setId(pid);
        hucRequestInterfase.executeStr(this, Good.class, HUCState.HUC_REQEUST_CODE_4,
                Request.Method.POST, UrlConfig.URL_PRO_GOODS,
                hucParameInterfase.getRequestParameter(baseVo), false);
    }


    private void initGoods() {
        hucRequestInterfase.executeStr(this, Good.class, HUCState.HUC_REQEUST_CODE_2, Request.Method.POST, UrlConfig.URL_PRO_GOODS, hucParameInterfase.getRequestParameter(new BaseVo()), false);
    }

    @Override
    public void OnBannerClick(int position) {
        if (ObjectUtil.isNotNull(bannerList) && bannerList.size() > 0) {
            Banner bannerVo = bannerList.get(position);
            String link = bannerVo.getPbLink();
            if (StrUtil.isNotEmpty(link) && !"null".equals(link)) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(link));
                // 检查是否有应用可以处理这个Intent
                if (intent.resolveActivity(this.getActivity().getPackageManager()) != null) {
                    startActivity(intent); // 打开浏览器

                } else {
                    // 如果没有找到应用程序，则提示用户
                    showToast("没有找到可以打开链接的应用程序");
                }
            }
        }

    }

    //加载Banner
    private void initBanners() {
        hucRequestInterfase.executeStr(this, Banner.class, HUCState.HUC_REQEUST_CODE_1, Request.Method.POST, UrlConfig.URL_PRO_BANNERS, hucParameInterfase.getRequestParameter(new BaseVo()), false);
    }



    private void initAd() {
        //Banner广告
        if (ObjectUtil.isNull(view)) {
            return;
        }
        ATNativeAdView viewGroup = view.findViewById(R.id.fl_content);
        String key = getSharedPreferences(RedisEnum.TA_KU.getKey());
        if (RedisEnum.TA_KU.getValue().equals(key)) {

            TaKuNativeAdHome taKuNativeAdHome = TaKuNativeAdHome.getInstance();
            taKuNativeAdHome.setmATNativeAdView(viewGroup);
            taKuNativeAdHome.setToken(getSharedPreferencesToken("token"));
            taKuNativeAdHome.showAd();

            if (UrlAddressConfig.shouldShowAd()) {
                TaKuInterstitialAdHome taKuInterstitialAdHome = TaKuInterstitialAdHome.getInstance();
                taKuInterstitialAdHome.setToken(getSharedPreferencesToken("token"));
                taKuInterstitialAdHome.showAd(this.getActivity());
            }
        } else {
            //信息流
            MediationFeedAd mediationFeedAd = MediationFeedAd.getInstance();
            mediationFeedAd.setFlFeed(viewGroup);
            mediationFeedAd.setActivity(this.getActivity());
            mediationFeedAd.showCacheFeedAd();
            if (UrlAddressConfig.shouldShowAd()) {
                //插屏广告
                MediationTablePlaqueAd mediationTablePlaqueAd = MediationTablePlaqueAd.getInstance();
                mediationTablePlaqueAd.showCacheInterstitialFullAd(this.getActivity(), null);
            }
        }
    }



}
